<template>
  <div class="settings-panel">
    <!-- 设置触发按钮 -->
    <div class="settings-trigger">
      <button
        @click="togglePanel"
        class="settings-button"
        :class="{ 'active': showPanel }"
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="3"/>
          <path d="M12 1v6m0 6v6m11-7h-6m-6 0H1m17-4a4 4 0 0 1-8 0 4 4 0 0 1 8 0zM7 21a4 4 0 0 1-8 0 4 4 0 0 1 8 0z"/>
        </svg>
      </button>
    </div>
    
    <!-- 设置面板 -->
    <Transition name="settings-panel">
      <div
        v-if="showPanel"
        class="panel-container"
        @click.stop
      >
        <!-- 面板头部 -->
        <div class="panel-header">
          <h3 class="panel-title">设置</h3>
          <button
            @click="closePanel"
            class="close-button"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="18" y1="6" x2="6" y2="18"/>
              <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>
        
        <!-- 设置内容 -->
        <div class="panel-content">
          <!-- 通用设置 -->
          <div class="settings-section">
            <h4 class="section-title">通用设置</h4>
            
            <!-- 主题设置 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">主题模式</label>
                <p class="setting-description">选择应用的外观主题</p>
              </div>
              <div class="setting-control">
                <select
                  v-model="settings.theme"
                  @change="updateSetting('theme', settings.theme)"
                  class="setting-select"
                >
                  <option value="light">浅色</option>
                  <option value="dark">深色</option>
                  <option value="auto">跟随系统</option>
                </select>
              </div>
            </div>
            
            <!-- 语言设置 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">语言</label>
                <p class="setting-description">选择界面显示语言</p>
              </div>
              <div class="setting-control">
                <select
                  v-model="settings.language"
                  @change="updateSetting('language', settings.language)"
                  class="setting-select"
                >
                  <option value="zh-CN">简体中文</option>
                  <option value="en-US">English</option>
                </select>
              </div>
            </div>
            
            <!-- 自动保存 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">自动保存</label>
                <p class="setting-description">自动保存用户输入和设置</p>
              </div>
              <div class="setting-control">
                <label class="toggle-switch">
                  <input
                    type="checkbox"
                    v-model="settings.autoSave"
                    @change="updateSetting('autoSave', settings.autoSave)"
                  >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
          
          <!-- 转换设置 -->
          <div class="settings-section">
            <h4 class="section-title">转换设置</h4>
            
            <!-- 默认输出格式 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">默认输出格式</label>
                <p class="setting-description">新建转换任务时的默认格式</p>
              </div>
              <div class="setting-control">
                <select
                  v-model="settings.defaultOutputFormat"
                  @change="updateSetting('defaultOutputFormat', settings.defaultOutputFormat)"
                  class="setting-select"
                >
                  <option value="docx">Word文档 (.docx)</option>
                  <option value="pdf">PDF文档 (.pdf)</option>
                  <option value="html">HTML网页 (.html)</option>
                  <option value="epub">电子书 (.epub)</option>
                </select>
              </div>
            </div>
            
            <!-- 质量设置 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">转换质量</label>
                <p class="setting-description">影响转换速度和输出质量</p>
              </div>
              <div class="setting-control">
                <select
                  v-model="settings.conversionQuality"
                  @change="updateSetting('conversionQuality', settings.conversionQuality)"
                  class="setting-select"
                >
                  <option value="fast">快速</option>
                  <option value="balanced">平衡</option>
                  <option value="high">高质量</option>
                </select>
              </div>
            </div>
            
            <!-- 自动下载 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">转换完成后自动下载</label>
                <p class="setting-description">任务完成后自动开始下载</p>
              </div>
              <div class="setting-control">
                <label class="toggle-switch">
                  <input
                    type="checkbox"
                    v-model="settings.autoDownload"
                    @change="updateSetting('autoDownload', settings.autoDownload)"
                  >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
          
          <!-- 通知设置 -->
          <div class="settings-section">
            <h4 class="section-title">通知设置</h4>
            
            <!-- 桌面通知 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">桌面通知</label>
                <p class="setting-description">允许显示桌面通知</p>
              </div>
              <div class="setting-control">
                <label class="toggle-switch">
                  <input
                    type="checkbox"
                    v-model="settings.desktopNotifications"
                    @change="updateSetting('desktopNotifications', settings.desktopNotifications)"
                  >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
            
            <!-- 声音提醒 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">声音提醒</label>
                <p class="setting-description">任务完成时播放提示音</p>
              </div>
              <div class="setting-control">
                <label class="toggle-switch">
                  <input
                    type="checkbox"
                    v-model="settings.soundNotifications"
                    @change="updateSetting('soundNotifications', settings.soundNotifications)"
                  >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
            
            <!-- 邮件通知 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">邮件通知</label>
                <p class="setting-description">重要事件的邮件提醒</p>
              </div>
              <div class="setting-control">
                <label class="toggle-switch">
                  <input
                    type="checkbox"
                    v-model="settings.emailNotifications"
                    @change="updateSetting('emailNotifications', settings.emailNotifications)"
                  >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
          
          <!-- 存储设置 -->
          <div class="settings-section">
            <h4 class="section-title">存储设置</h4>
            
            <!-- 文件保留时间 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">文件保留时间</label>
                <p class="setting-description">转换后的文件在服务器保存时长</p>
              </div>
              <div class="setting-control">
                <select
                  v-model="settings.fileRetentionDays"
                  @change="updateSetting('fileRetentionDays', settings.fileRetentionDays)"
                  class="setting-select"
                >
                  <option :value="7">7天</option>
                  <option :value="30">30天</option>
                  <option :value="90">90天</option>
                  <option :value="365">1年</option>
                </select>
              </div>
            </div>
            
            <!-- 自动清理 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">自动清理本地缓存</label>
                <p class="setting-description">定期清理浏览器缓存数据</p>
              </div>
              <div class="setting-control">
                <label class="toggle-switch">
                  <input
                    type="checkbox"
                    v-model="settings.autoCleanCache"
                    @change="updateSetting('autoCleanCache', settings.autoCleanCache)"
                  >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
          
          <!-- 高级设置 -->
          <div class="settings-section">
            <h4 class="section-title">高级设置</h4>
            
            <!-- 并发任务数 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">最大并发任务数</label>
                <p class="setting-description">同时进行的转换任务数量限制</p>
              </div>
              <div class="setting-control">
                <select
                  v-model="settings.maxConcurrentTasks"
                  @change="updateSetting('maxConcurrentTasks', settings.maxConcurrentTasks)"
                  class="setting-select"
                >
                  <option :value="1">1个</option>
                  <option :value="2">2个</option>
                  <option :value="3">3个</option>
                  <option :value="5">5个</option>
                </select>
              </div>
            </div>
            
            <!-- 调试模式 -->
            <div class="setting-item">
              <div class="setting-info">
                <label class="setting-label">调试模式</label>
                <p class="setting-description">显示详细的调试信息</p>
              </div>
              <div class="setting-control">
                <label class="toggle-switch">
                  <input
                    type="checkbox"
                    v-model="settings.debugMode"
                    @change="updateSetting('debugMode', settings.debugMode)"
                  >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 面板底部 -->
        <div class="panel-footer">
          <div class="footer-actions">
            <button
              @click="resetToDefaults"
              class="reset-button"
              :disabled="resetting"
            >
              {{ resetting ? '重置中...' : '恢复默认' }}
            </button>
            
            <button
              @click="exportSettings"
              class="export-button"
            >
              导出设置
            </button>
            
            <input
              ref="importInput"
              type="file"
              accept=".json"
              @change="importSettings"
              style="display: none"
            >
            
            <button
              @click="$refs.importInput?.click()"
              class="import-button"
            >
              导入设置
            </button>
          </div>
          
          <div class="footer-info">
            <span class="save-status" :class="{ 'saving': saving }">
              {{ saving ? '保存中...' : '设置已自动保存' }}
            </span>
          </div>
        </div>
      </div>
    </Transition>
    
    <!-- 遮罩层 -->
    <Transition name="settings-overlay">
      <div
        v-if="showPanel"
        class="settings-overlay"
        @click="closePanel"
      ></div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useSettingsStore } from '@/stores/settings'

interface Settings {
  theme: 'light' | 'dark' | 'auto'
  language: 'zh-CN' | 'en-US'
  autoSave: boolean
  defaultOutputFormat: 'docx' | 'pdf' | 'html' | 'epub'
  conversionQuality: 'fast' | 'balanced' | 'high'
  autoDownload: boolean
  desktopNotifications: boolean
  soundNotifications: boolean
  emailNotifications: boolean
  fileRetentionDays: number
  autoCleanCache: boolean
  maxConcurrentTasks: number
  debugMode: boolean
}

// Store
const settingsStore = useSettingsStore()

// 响应式数据
const showPanel = ref(false)
const saving = ref(false)
const resetting = ref(false)
const importInput = ref<HTMLInputElement>()

// 设置数据
const settings = reactive<Settings>({
  theme: 'light',
  language: 'zh-CN',
  autoSave: true,
  defaultOutputFormat: 'docx',
  conversionQuality: 'balanced',
  autoDownload: false,
  desktopNotifications: true,
  soundNotifications: true,
  emailNotifications: false,
  fileRetentionDays: 30,
  autoCleanCache: true,
  maxConcurrentTasks: 2,
  debugMode: false
})

// 默认设置
const defaultSettings: Settings = {
  theme: 'light',
  language: 'zh-CN',
  autoSave: true,
  defaultOutputFormat: 'docx',
  conversionQuality: 'balanced',
  autoDownload: false,
  desktopNotifications: true,
  soundNotifications: true,
  emailNotifications: false,
  fileRetentionDays: 30,
  autoCleanCache: true,
  maxConcurrentTasks: 2,
  debugMode: false
}

// 方法
const togglePanel = () => {
  showPanel.value = !showPanel.value
}

const closePanel = () => {
  showPanel.value = false
}

const updateSetting = async (key: keyof Settings, value: any) => {
  saving.value = true
  
  try {
    // 更新本地设置
    settings[key] = value
    
    // 保存到store
    await settingsStore.updateSetting(key, value)
    
    // 应用设置
    applySettings()
    
  } catch (error) {
    console.error('Failed to update setting:', error)
    // 回滚设置
    loadSettings()
  } finally {
    saving.value = false
  }
}

const loadSettings = () => {
  const savedSettings = settingsStore.getSettings()
  Object.assign(settings, { ...defaultSettings, ...savedSettings })
  applySettings()
}

const applySettings = () => {
  // 应用主题
  if (settings.theme === 'dark') {
    document.documentElement.classList.add('dark')
  } else if (settings.theme === 'light') {
    document.documentElement.classList.remove('dark')
  } else {
    // 跟随系统
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    document.documentElement.classList.toggle('dark', prefersDark)
  }
  
  // 应用语言设置
  document.documentElement.lang = settings.language
  
  // 应用调试模式
  if (settings.debugMode) {
    console.log('Debug mode enabled')
    window.DEBUG = true
  } else {
    window.DEBUG = false
  }
  
  // 请求桌面通知权限
  if (settings.desktopNotifications && 'Notification' in window) {
    if (Notification.permission === 'default') {
      Notification.requestPermission()
    }
  }
}

const resetToDefaults = async () => {
  if (!confirm('确定要恢复所有设置到默认值吗？')) return
  
  resetting.value = true
  
  try {
    Object.assign(settings, defaultSettings)
    await settingsStore.resetSettings()
    applySettings()
  } catch (error) {
    console.error('Failed to reset settings:', error)
  } finally {
    resetting.value = false
  }
}

const exportSettings = () => {
  try {
    const settingsData = {
      version: '1.0',
      timestamp: new Date().toISOString(),
      settings: { ...settings }
    }
    
    const blob = new Blob([JSON.stringify(settingsData, null, 2)], {
      type: 'application/json'
    })
    
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `md2dockit-settings-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
  } catch (error) {
    console.error('Failed to export settings:', error)
    alert('导出设置失败')
  }
}

const importSettings = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return
  
  try {
    const text = await file.text()
    const data = JSON.parse(text)
    
    if (data.settings) {
      // 验证设置数据
      const validSettings = { ...defaultSettings }
      for (const [key, value] of Object.entries(data.settings)) {
        if (key in validSettings) {
          validSettings[key as keyof Settings] = value as any
        }
      }
      
      Object.assign(settings, validSettings)
      await settingsStore.updateSettings(validSettings)
      applySettings()
      
      alert('设置导入成功')
    } else {
      throw new Error('Invalid settings file format')
    }
    
  } catch (error) {
    console.error('Failed to import settings:', error)
    alert('导入设置失败，请检查文件格式')
  }
  
  // 清空文件输入
  if (importInput.value) {
    importInput.value.value = ''
  }
}

// 监听系统主题变化
const handleSystemThemeChange = (e: MediaQueryListEvent) => {
  if (settings.theme === 'auto') {
    document.documentElement.classList.toggle('dark', e.matches)
  }
}

// 点击外部关闭面板
const handleClickOutside = (event: Event) => {
  const target = event.target as Element
  if (!target.closest('.settings-panel')) {
    closePanel()
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  
  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', handleSystemThemeChange)
  
  // 加载设置
  loadSettings()
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.removeEventListener('change', handleSystemThemeChange)
})

// 监听设置变化
watch(settings, () => {
  // 防抖保存
  clearTimeout(window.settingsSaveTimeout)
  window.settingsSaveTimeout = setTimeout(() => {
    settingsStore.saveSettings(settings)
  }, 1000)
}, { deep: true })
</script>

<style scoped>
.settings-panel {
  position: relative;
}

.settings-trigger {
  position: relative;
}

.settings-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: none;
  background: transparent;
  border-radius: 8px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;
}

.settings-button:hover {
  background: #f3f4f6;
  color: #374151;
}

.settings-button.active {
  background: #3b82f6;
  color: white;
}

.panel-container {
  position: absolute;
  top: 100%;
  right: 0;
  width: 420px;
  max-height: 600px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  margin-top: 8px;
}

.settings-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

/* 面板头部 */
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #111827;
  margin: 0;
}

.close-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border: none;
  background: transparent;
  color: #6b7280;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.close-button:hover {
  background: #f3f4f6;
  color: #374151;
}

/* 面板内容 */
.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.settings-section {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
}

.settings-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #111827;
  margin: 0 0 16px 0;
}

.setting-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 16px;
}

.setting-item:last-child {
  margin-bottom: 0;
}

.setting-info {
  flex: 1;
  min-width: 0;
}

.setting-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 2px;
}

.setting-description {
  font-size: 12px;
  color: #6b7280;
  margin: 0;
  line-height: 1.4;
}

.setting-control {
  flex-shrink: 0;
}

.setting-select {
  padding: 6px 12px;
  font-size: 14px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  color: #374151;
  cursor: pointer;
  min-width: 120px;
}

.setting-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 切换开关 */
.toggle-switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
  cursor: pointer;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-slider {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #d1d5db;
  border-radius: 24px;
  transition: all 0.2s ease;
}

.toggle-slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background: white;
  border-radius: 50%;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.toggle-switch input:checked + .toggle-slider {
  background: #3b82f6;
}

.toggle-switch input:checked + .toggle-slider:before {
  transform: translateX(20px);
}

/* 面板底部 */
.panel-footer {
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
}

.footer-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.reset-button,
.export-button,
.import-button {
  padding: 6px 12px;
  font-size: 12px;
  border: 1px solid #d1d5db;
  background: white;
  color: #374151;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.reset-button:hover,
.export-button:hover,
.import-button:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.reset-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.footer-info {
  text-align: center;
}

.save-status {
  font-size: 11px;
  color: #6b7280;
  transition: all 0.2s ease;
}

.save-status.saving {
  color: #3b82f6;
}

/* 动画 */
.settings-panel-enter-active,
.settings-panel-leave-active {
  transition: all 0.3s ease;
}

.settings-panel-enter-from {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

.settings-panel-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

.settings-overlay-enter-active,
.settings-overlay-leave-active {
  transition: opacity 0.3s ease;
}

.settings-overlay-enter-from,
.settings-overlay-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .panel-container {
    width: 360px;
    max-height: 500px;
  }
  
  .panel-header,
  .settings-section,
  .panel-footer {
    padding-left: 16px;
    padding-right: 16px;
  }
  
  .setting-item {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .setting-control {
    align-self: flex-end;
  }
  
  .footer-actions {
    flex-wrap: wrap;
  }
}

/* 深色主题 */
@media (prefers-color-scheme: dark) {
  .panel-container {
    background: #1f2937;
    border-color: #374151;
  }
  
  .panel-title {
    color: #f9fafb;
  }
  
  .section-title {
    color: #f3f4f6;
  }
  
  .setting-label {
    color: #e5e7eb;
  }
  
  .setting-description {
    color: #9ca3af;
  }
  
  .setting-select {
    background: #374151;
    border-color: #4b5563;
    color: #f3f4f6;
  }
  
  .panel-footer {
    background: #111827;
    border-color: #374151;
  }
  
  .reset-button,
  .export-button,
  .import-button {
    background: #374151;
    border-color: #4b5563;
    color: #f3f4f6;
  }
  
  .reset-button:hover,
  .export-button:hover,
  .import-button:hover {
    background: #4b5563;
  }
}
</style>